package map.android.baidu.carpool.reservation;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.Locale;

import com.baidu.components.api.extra.APIProxy;

import android.app.Activity;
import android.app.Dialog;
import android.view.Display;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.view.Window;
import android.view.WindowManager;
import android.widget.LinearLayout;
import android.widget.TextView;
import map.android.baidu.carpool.R;
import map.android.baidu.carpool.widget.wheel.OnWheelChangedListener;
import map.android.baidu.carpool.widget.wheel.WheelView;

public class CarDateTimeDialog extends Dialog {
    private Activity mActivity;
    public static final boolean VISIBLE = true;
    public static final boolean GONE = false;

    private WheelView hoursWheelView = null;
    private WheelView minsWheelView = null;
    private WheelView dayWheelView = null;

    private MinsWheelAdapter minAdapter = null;
    private HoursWheelAdapter hourAdapter = null;
    private DaysWheelAdapter dayAdapter = null;

    private ArrayList<Integer> mEmptyList = null;

    private OnSelectDateTimeListener dateTimeListener;
    private OnSelectNowListener todayListener;

    private boolean dayShow = true;
    private boolean hourShow = true;
    private boolean minShow = true;

    private static final double SCALE = 1.0;

    private Calendar mCalendarNow;
    private int mHourOfDay;
    private int mMinute;

    private int mMinuteData[] = {0, 10, 20, 30, 40, 50};
    private static final int MAX_MINUTE = 50;

    private static final int MAX_HOUR = 23;

    private int MAX_DAY = 2;

    private static final long DAY_IN_MILLISECONDS = 24 * 60 * 60 * 1000;

    private static final int BUFFER_MINUTE = 5;

    private Calendar mCalendarSelected = null;

    public interface OnSelectDateTimeListener {
        void dateTimeSelected(Calendar c);
    }

    public interface OnSelectNowListener {
        void selectNow();
    }

    public CarDateTimeDialog(Activity activity, OnSelectNowListener selectTodayListener,
                             OnSelectDateTimeListener selectDateTimeListener, int style, boolean dayshow,
                             boolean hourshow,
                             boolean minshow, int dateLimit) {
        super(activity, style);
        this.mActivity = activity;
        this.todayListener = selectTodayListener;
        this.dateTimeListener = selectDateTimeListener;
        this.dayShow = dayshow;
        this.hourShow = hourshow;
        this.minShow = minshow;
        this.MAX_DAY = dateLimit - 1;

        init();
    }

    private void initNowTime() {
        mCalendarSelected = Calendar.getInstance(Locale.CHINESE);
        mCalendarSelected.add(mCalendarSelected.MINUTE, 30);
        mCalendarSelected.setTimeInMillis(mCalendarSelected.getTimeInMillis() + (10 * 60 * 1000 - mCalendarSelected
                .getTimeInMillis() %
                (10 * 60 * 1000)));
        if (mCalendarSelected.get(Calendar.HOUR_OF_DAY) < 6) {
            mCalendarSelected.set(Calendar.HOUR_OF_DAY, 6);
            mCalendarSelected.set(Calendar.MINUTE, 0);
            mCalendarSelected.set(Calendar.MILLISECOND, 0);

        }

        if (mCalendarSelected.get(Calendar.HOUR_OF_DAY) > 22) {
            mCalendarSelected.add(Calendar.DAY_OF_MONTH, 1);
            mCalendarSelected.set(Calendar.HOUR_OF_DAY, 6);
            mCalendarSelected.set(Calendar.MINUTE, 0);
            mCalendarSelected.set(Calendar.MILLISECOND, 0);

        }

    }

    @SuppressWarnings("deprecation")
    private void init() {
        initNowTime();
        LayoutInflater inflater = APIProxy.res().getInflater();
        View view = inflater.inflate(R.layout.car_dialog_reservation_datetime_layout, null);

        setContentView(view);

        WindowManager windowManager = mActivity.getWindowManager();
        Display display = windowManager.getDefaultDisplay();

        Window window = getWindow();
        WindowManager.LayoutParams attributes = window.getAttributes();
        attributes.gravity = Gravity.BOTTOM;
        attributes.height = WindowManager.LayoutParams.WRAP_CONTENT;
        attributes.width = (int) (display.getWidth() * SCALE);
        window.setAttributes(attributes);

        initViewUseNew(view);
    }

    private void initViewUseNew(View view) {
        try {

            mEmptyList = new ArrayList<Integer>();
            mEmptyList.add(Integer.MAX_VALUE);

            LinearLayout wheelContainerView = (LinearLayout) view.findViewById(R.id.car_wheel_container);
            LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT,
                    LayoutParams.WRAP_CONTENT);
            lp.weight = 0.33f;
            /**
             * 显示天数
             */
            dayAdapter = new DaysWheelAdapter(mActivity);
            dayAdapter.setData(getDayList());

            dayWheelView = new WheelView(mActivity);
            wheelContainerView.addView(dayWheelView, lp);
            dayWheelView.setCurrentItem(0);
            dayWheelView.setViewAdapter(dayAdapter);
            dayWheelView.setVisibility(dayShow ? View.VISIBLE : View.GONE);
            dayAdapter.setItemResource(R.layout.car_wheel_text_item);
            dayAdapter.setItemTextResource(R.id.car_reservation_wheelview_text);
            dayWheelView.addChangingListener(new OnWheelChangedListener() {
                @Override
                public void onChanged(WheelView wheel, int oldValue, int newValue) {
                    int currentHourItem = hoursWheelView.getCurrentItem();
                    int item = wheel.getCurrentItem();
                    Calendar c = dayAdapter.getItem(item);
                    if (c == null) {
                        hourAdapter.setData(mEmptyList);
                    } else {
                        hourAdapter.setData(getHourList(dayAdapter.getItem(item)));
                    }

                   /* if (currentHourItem >= hourAdapter.getItemsCount()) {
                        hoursWheelView.setCurrentItem(hourAdapter.getItemsCount() - 1);
                    }*/
                    if (hourAdapter.getItemsCount() > 0) {
                        hoursWheelView.setCurrentItem(0);
                    }

                    mHoursWheelViewChangedlistener.onChanged(hoursWheelView, 0, 0);
                }
            });
            /**
             * 小时数
             */

            hoursWheelView = new WheelView(mActivity);
            wheelContainerView.addView(hoursWheelView, lp);

            hoursWheelView.setCurrentItem(0);
            hourAdapter = new HoursWheelAdapter(mActivity);
            hourAdapter.setData(getHourList(mCalendarSelected));
            hourAdapter.setItemResource(R.layout.car_wheel_text_item);
            hourAdapter.setItemTextResource(R.id.car_reservation_wheelview_text);
            hoursWheelView.setViewAdapter(hourAdapter);
            hoursWheelView.setVisibility(hourShow ? View.VISIBLE : View.GONE);
            hoursWheelView.addChangingListener(mHoursWheelViewChangedlistener);
            /**
             * 分钟数
             */
            minsWheelView = new WheelView(mActivity);
            wheelContainerView.addView(minsWheelView, lp);
            minsWheelView.setCurrentItem(0);

            minAdapter = new MinsWheelAdapter(mActivity);
            minAdapter.setData(
                    getMinuteList(mCalendarSelected, hourAdapter.getItemValue(hoursWheelView.getCurrentItem())));

            minAdapter.setItemResource(R.layout.car_wheel_text_item);
            minAdapter.setItemTextResource(R.id.car_reservation_wheelview_text);
            minsWheelView.setViewAdapter(minAdapter);
            minsWheelView.setVisibility(minShow ? View.VISIBLE : View.GONE);

            dayWheelView.setCurrentItem(0);

            TextView okTextView = (TextView) view.findViewById(R.id.car_reservation_wheel_ok_textview);
            okTextView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (dateTimeListener != null) {
                        int dayCurrentItem = dayWheelView.getCurrentItem();
                        Calendar calendar = dayAdapter.getItem(dayCurrentItem);
                        if (calendar == null) {
                            todayListener.selectNow();
                        } else {

                            int hour = hourAdapter.getItemValue(hoursWheelView.getCurrentItem());
                            int min = minAdapter.getItemValue(minsWheelView.getCurrentItem());
                            calendar.set(Calendar.HOUR_OF_DAY, hour);
                            calendar.set(Calendar.MINUTE, min);
                            dateTimeListener.dateTimeSelected(calendar);
                        }
                    }

                    dismiss();
                }
            });

            TextView cancelTextView = (TextView) view.findViewById(R.id.car_reservation_wheel_cancel_textview);
            cancelTextView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    dismiss();
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    OnWheelChangedListener mHoursWheelViewChangedlistener = new OnWheelChangedListener() {
        @Override
        public void onChanged(WheelView wheel, int oldValue, int newValue) {
            int currentMinute = minsWheelView.getCurrentItem();
            Calendar c = dayAdapter.getItem(dayWheelView.getCurrentItem());
            if (c == null) {
                minAdapter.setData(mEmptyList);
            } else {
                if (isToday(c) && c.get(Calendar.HOUR_OF_DAY) <= mCalendarSelected.get(Calendar.HOUR_OF_DAY)) {
                    c.set(Calendar.HOUR_OF_DAY, mCalendarSelected.get(Calendar.HOUR_OF_DAY));
                    c.set(Calendar.MINUTE, mCalendarSelected.get(Calendar.MINUTE));
                }
                minAdapter.setData(getMinuteList(c, hourAdapter.getItemValue(hoursWheelView.getCurrentItem())));
            }
            if (minAdapter.getItemsCount() > 0) {
                minsWheelView.setCurrentItem(0);
            }

            /*if (currentMinute >= minAdapter.getItemsCount()) {
                minsWheelView.setCurrentItem(minAdapter.getItemsCount() - 1);
            }*/
        }
    };

    List<Calendar> getDayList() {
        List<Calendar> list = new ArrayList<Calendar>();
        //list.add(null);
        mCalendarNow = Calendar.getInstance(Locale.CHINESE);
        mHourOfDay = mCalendarNow.get(Calendar.HOUR_OF_DAY);
        mMinute = mCalendarNow.get(Calendar.MINUTE);
        // mCalendarNow = mCalendarSelected;
        // 如果现在的时间是在23:00之前，并且不是在22:40分之后，那么今天是可选的，将今天加入list中:6--22:50
        // if ((mHourOfDay > 6 && mHourOfDay < 23) && !(mHourOfDay == 22 && mMinute >= 50)) {
        list.add(mCalendarNow);
        dayAdapter.setmTodayStatus(true);
        // }
        Calendar today = mCalendarNow;

        // 将往后的2天都加入list中
        for (int i = 0; i < MAX_DAY; i++) {
            Calendar calendar = Calendar.getInstance();
            calendar.setTimeInMillis(today.getTimeInMillis() + DAY_IN_MILLISECONDS);
            today = calendar;
            list.add(today);
        }
        return list;
    }

    List<Integer> getHourList(Calendar calendar) {
        List<Integer> list = new ArrayList<Integer>();
        if (isToday(calendar)) {
            int start = 0;
            start = mCalendarSelected.get(Calendar.HOUR_OF_DAY);
            for (int i = start; i < 23; i++) {
                list.add(i);
            }
        } else {
            for (int i = 6; i < 23; i++) {
                list.add(i);
            }
        }
        return list;
    }

    List<Integer> getMinuteList(Calendar calendar, int hourSelected) {
        List<Integer> list = new ArrayList<Integer>();
        int a = hourSelected;
        int b = calendar.get(Calendar.HOUR_OF_DAY);
        if (isToday(calendar) && (hourSelected == calendar.get(Calendar.HOUR_OF_DAY))) {
            for (int i = 0; i < mMinuteData.length; i++) {
                if (mMinuteData[i] >= calendar.get(Calendar.MINUTE)) {
                    list.add(mMinuteData[i]);
                }
            }

        } else {
            for (int i = 0; i < mMinuteData.length; i++) {
                list.add(mMinuteData[i]);
            }
        }
        return list;
    }

    boolean isToday(Calendar calendar) {
        return mCalendarNow.get(Calendar.YEAR) == calendar.get(Calendar.YEAR)
                && mCalendarNow.get(Calendar.MONTH) == calendar.get(Calendar.MONTH)
                && mCalendarNow.get(Calendar.DAY_OF_MONTH) == calendar.get(Calendar.DAY_OF_MONTH);
    }

    boolean isTomorrow(Calendar calendar) {

        return calendar.after(mCalendarNow)
                && calendar.getTimeInMillis() - mCalendarNow.getTimeInMillis() == DAY_IN_MILLISECONDS;
    }

    boolean isAfter(Calendar calendar) {
        return calendar.after(mCalendarNow)
                && calendar.getTimeInMillis() - mCalendarNow.getTimeInMillis() == 2 * DAY_IN_MILLISECONDS;

    }

}
